package com.binguo.thirdPay.hzShiMing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuritian
 * @Title: HZShiMingFaceService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-07-1714:32
 */
@Service
public class HZShiMingFaceService {

    //上线APPID
    private static String APPID = "10000002";
    //上线URL
    private static String URL = "https://face.96225.com/api/smk";

    //测试APPID
//    private static String APPID = "20000001";

    //测试URL
//    private static String URL = "http://115.236.162.164:28080/api/smk";



    public static void main(String[] args) {

    }
    //人脸查询
    public JSONObject queryFace(String base64Img){

        SortedMap<String, String> messageMap = getHeadMap();
        String sign = null;
        try {
            System.out.println("待签名字符串"+JSON.toJSONString(messageMap));
            sign = RSAUtil.rsaFaceSign(JSON.toJSONString(messageMap));
        } catch (Exception e) {
            return null;
        }
        messageMap.put("sign",sign);
        messageMap.put("photo",base64Img);
        JSONObject result = getRessultJson("/face/otn",JSON.toJSONString(messageMap));
        return result;
    }
    //String idCard,
    //String idType,
    //String phoneNo,
    //String custName,
    //String sex

    public void createPerson(String base64Img){
        SortedMap<String, String> messageMap = getHeadMap();
        messageMap.put("idCard","654223199402031514");
        messageMap.put("idType","01");
        messageMap.put("phoneNo","13588204717");
        messageMap.put("custName","刘朝政");
        messageMap.put("sex","1");

        String sign = null;
        try {
            System.out.println("待签名字符串"+JSON.toJSONString(messageMap));
            sign = RSAUtil.rsaFaceSign(JSON.toJSONString(messageMap));
        } catch (Exception e) {

        }
        System.out.println(getSignStr(messageMap));
        messageMap.put("sign",sign);
        messageMap.put("photo",base64Img);
        JSONObject result = getRessultJson("/face/useradd",JSON.toJSONString(messageMap));
        System.out.println(result.toJSONString());
    }

    //删除人脸
    public void deletePerson(String idCard,
                             String idType){
        SortedMap<String, String> messageMap = getHeadMap();
        messageMap.put("idCard",idCard);
        messageMap.put("idType",idType);
        String sign = null;
        try {
            System.out.println("待签名字符串"+JSON.toJSONString(messageMap));
            sign = RSAUtil.rsaFaceSign(JSON.toJSONString(messageMap));
        } catch (Exception e) {

        }
        System.out.println(getSignStr(messageMap));
        messageMap.put("sign",sign);
        JSONObject result = getRessultJson("/face/userdel",JSON.toJSONString(messageMap));
        System.out.println(result.toJSONString());

    }

    public void getPublicKey(String pubkey){
        SortedMap<String, String> messageMap = getHeadMap();
        messageMap.put("pubKey",pubkey);
        JSONObject result = getRessultJson("/appbind",JSON.toJSONString(messageMap));
        System.out.println(result.toJSONString());

    }

    private SortedMap<String, String> getHeadMap(){
        Date now = new Date();
        SimpleDateFormat date = new SimpleDateFormat("yyyyMMddHHmmss");

        SortedMap<String, String> messageMap = new TreeMap<>();
        String reqSeq =  "YunPeng" + System.currentTimeMillis();
        messageMap.put("faceAppId", APPID);
        messageMap.put("reqSeq", reqSeq);
        messageMap.put("reqDateTime", date.format(now));

        return messageMap;
    }

    private String getSignStr(SortedMap<String, String> messageMap){
        Integer count = 0;
        StringBuilder signStr = new StringBuilder();
        for (String key : messageMap.keySet()) {
            signStr.append(count == 0 ? "" : "&").append(key).append("=").append(messageMap.get(key));
            count++;
        }
        System.out.println(signStr.toString());
        return signStr.toString();
    }

    private JSONObject getRessultJson(String methodURL, String messageMapStr){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(messageMapStr, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(URL+methodURL, entity, String.class);
        String result = resp.getBody();
        System.out.println(result);
        JSONObject jsonResult = JSONObject.parseObject(result);
        String sign = jsonResult.getString("sign");
        jsonResult.remove("sign");
        try {
            if (RSAUtil.rsaFaceCheck(jsonResult.toJSONString(), sign)) {
                return jsonResult.getJSONObject("data");
            }else {
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }

    private boolean generateImage(String imgStr, String path) {
        if(imgStr == null){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try{
            //解密
            byte[] b = decoder.decodeBuffer(imgStr);
            //处理数据
            for (int i = 0;i<b.length;++i){
                if(b[i]<0){
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


}
